<?php

namespace Admin\Controller;

class UserController extends AdminbaseController {

    protected $userModel, $roleModel, $roleUserModel,$shopModel,$adminShop;

    function _initialize() {
        parent::_initialize();
        $this->userModel = D("admin");
        $this->roleModel = D("AdminRole");
        $this->roleUserModel = D("AdminRoleUser");
    }

    /**
     *  管理员管理，有add添加，edit修改，delete删除
     */
    function index() {

        $count = $this->userModel->count();
        $page = $this->page($count, 20);
        $users = $this->userModel
                ->limit($page->firstRow . ',' . $page->listRows)
                ->select();
        $allRoleList = D("AdminRole")->select();
        $this->assign("page", $page->show('Admin'));
        $this->assign("users", $users);
        $this->assign("allRoleList", $allRoleList);
        $this->display();
    }

    function employee() {

        $userId=$_SESSION['ADMIN_ID'];
        $user=D("admin")->where("user_id=$userId")->find();

        $count = $this->userModel->where(array("enterprise_code" => $user["enterprise_code"]))->count();

        $page = $this->page($count, 20);
        $users = $this->userModel
            ->where(array("enterprise_code" => $user["enterprise_code"]))
            ->order("granted asc")
            ->limit($page->firstRow . ',' . $page->listRows)
            ->select();
        $allRoleList = D("AdminRole")->select();
        $this->assign("page", $page->show('Admin'));
        $this->assign("user", $user);
        $this->assign("users", $users);
        $this->assign("allRoleList", $allRoleList);
        $this->display();
    }

    public function updateInfo() {
        $id = $_REQUEST["id"];
        $admin = $this->userModel->where(array("employee_id" => $id))->find();

        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".access_token()."&openid=".$admin["openid"]."&lang=zh_CN";
        $info = json_decode(curl($url),true);

//        $nicknameTmp = json_encode($info["nickname"]);
//        $nicknameTmp = preg_replace_callback("#(\\\ud[0-9a-f]{3})#i",function($r){ return ""; },$nicknameTmp);
//        $nicknameNoEmoji = json_decode($nicknameTmp);

        if(!isNullOrEmpty($info["headimgurl"])){
            $admin["headimgurl"] = $info["headimgurl"];
        }

        $this->userModel->where(array("employee_id" => $id))->save($admin);
        $this->success("刷新用户信息成功", U("user/employee"));
    }

    /**
     *  添加管理员
     */
    function add() {
        $userId=$_SESSION['ADMIN_ID'];
        $user = $this->userModel->where(array("user_id" => $userId))->find();
        $roles = $this->roleModel->where("status=1")->order("id desc")->select();
        $enterprise = D("enterprise")->where(array('enterprise_code'=>$user["enterprise_code"]))->find();
        $enterpriseRole = explode(',', $enterprise["role_list"]);
        foreach ($roles as $key=>$singleRole){
            if(!in_array($singleRole["id"], $enterpriseRole)){
                unset($roles[$key]);
            }
        }
        $this->assign("roles", $roles);
        $this->display();
    }

    /**
     *  添加管理员
     */
    function add_post() {
        if (IS_POST) {
            if (!empty($_POST['role_id']) && is_array($_POST['role_id'])) {
                $roleIds = I('post.role_id');
                $name = I('post.name');
                $password = I('post.password');

                $user = $this->userModel->where(array('name' => $name))->find();

                if(!isNullOrEmpty($user)) {
                    $this->error("该用户名已存在");
                }
                
                $data['name'] = $name;
                $data['password'] = md5($password);
                $data['create_time'] = getCurrentDate();
                $userId = $this->userModel->add($data);
                
                $userRole = $this->roleUserModel->where(array("user_id" => $userId))->find();
                if (!isNullOrEmpty($userRole)) {
                    $this->error("该用户已存在角色，请编辑修改!");
                }

                foreach ($roleIds as $roleId) {
                    $this->roleUserModel->add(array("role_id" => $roleId, "user_id" => $userId));
                }
                $this->success("添加成功", U("user/employee"));
            } else {
                $this->error("请为此用户指定角色!");
            }
        }
    }

    /**
     *  编辑管理员
     */
    function edit() {
//        $userId = intval(I("get.id"));
        $userId = $_REQUEST["id"];

//        $role_ids = $this->roleUserModel->where(array("user_id" => $userId))->getField("role_id", true);
        $user = $this->userModel->where(array("user_id" => $userId))->find();
        if($user["granted"] == 1){
            $role_ids = explode(',', $user["role"]);
        }else{
            $role_ids = explode(',', $user["pre_role"]);
        }
        $updater = $this->userModel->where(array("employee_id" => $user["update_id"]))->find();

        $roles = $this->roleModel->order("id asc")->select();

        $enterprise = D("enterprise")->where(array('enterprise_code'=>$user["enterprise_code"]))->find();
        $enterpriseRole = explode(',', $enterprise["role_list"]);
        foreach ($roles as $key=>$singleRole){
            if(!in_array($singleRole["id"], $enterpriseRole)){
                unset($roles[$key]);
            }
        }

        $agentIdArr = D('Agent')
            ->where(array('enterprise_code'=>$user['enterprise_code']))
            ->select();
        $userAgentIdArr = explode(",", $user["agent_id"]);

        $list = array();
        foreach ($agentIdArr as $agent){
            if(in_array($agent["agent_id"], $userAgentIdArr)){
                $list[] = array("agent_id" => $agent["agent_id"], "agent_name" => $agent["agent_name"], "has_agent" => 1);
            }else{
                $list[] = array("agent_id" => $agent["agent_id"], "agent_name" => $agent["agent_name"]);
            }

        }
        $this->assign("list", $list);

        $this->assign("roles", $roles);
        $this->assign("role_ids", $role_ids);
        $this->assign('user', $user);
        $this->assign('updateName', $updater["admin_name"]);
        $this->display();
    }

    /**
     *  编辑管理员
     */
    function edit_post() {
        if (IS_POST) {
            if (!empty($_POST['role_id']) && is_array($_POST['role_id'])) {
                $role_ids = I('post.role_id');
                $userId = I('post.user_id');
                $name = I('post.name');
                $password = I('post.password');

                $user = $this->userModel->where(array('user_id'=>$userId))->find();

                if($user["granted"] != 1){
                    $notifyData["openid"] = $user["openid"];
                    $notifyData["first"] = "尊敬的用户：".$user["admin_name"]."，您的【".$user["enterprise_name"]."】企业用户注册信息申请状态已更新。";
                    $notifyData["keyword1"] = "申请部门：";
                    $allRoleList = D("AdminRole")->select();
                    foreach($allRoleList as $role){
                        if(in_array($role["id"],$role_ids)){
                            $notifyData["keyword1"].= $role["name"]."；";
                        }
                    }
                    $notifyData["keyword2"] = "审批通过";
                    $notifyData["keyword3"] = getCurrentDate();
//                    $notifyData["remark"] = "备注：".I("post.note")."。";
                }
                if(!isNullOrEmpty($name)) {
                    $existMap['user_id'] = array('neq', $userId);
                    $existMap['name'] = $name;

                    $existUser = $this->userModel->where($existMap)->find();

                    if (!isNullOrEmpty($existUser)) {
                        $this->error("已经存在该用户名！");
                    }
                    $user['name'] = $name;
                    if(!isNullOrEmpty($password)){
                        $user['password'] = md5($password);
                    }
                }
                $user['admin_name'] = I('post.adminName');
                $user['mobile'] = I('post.mobile');
                $user["signimgurl"] = I('post.signimgurl');
                
                $user['pre_role'] = "";
                $user['note'] = "";
                $user['granted'] = 1;
                $user['update_time'] = getCurrentDate();
                $adminUsers_obj= M("admin");
                $adminUserId=$_SESSION['ADMIN_ID'];
                $adminUser=$adminUsers_obj->where("user_id=$adminUserId")->find();
                $user['update_id'] = $adminUser["employee_id"];
                
                $this->roleUserModel->where(array("user_id" => $userId))->delete();

                $user['role'] = "";
                foreach ($role_ids as $role_id) {
                    $this->roleUserModel->add(array("role_id" => $role_id, "user_id" => $userId));
                    $user['role'].=$role_id;
                    if($role_id != end($role_ids)) {
                        $user['role'].=",";
                    }
                }
                $user["agent_id"] = I('post.agentId');
                $this->userModel->where(array('user_id'=>$userId))->save($user);

                if(!isNullOrEmpty($notifyData)){
                    progressNotify($notifyData);
                }

                $this->success("保存成功！", U("user/employee"));
            } else {
                $this->error("请为此用户指定角色！");
            }
        }
    }

    /**
    *  删除
    */
   function delete() {
       $userId = intval(I("get.id"));
       $this->roleUserModel->where(array("user_id" => $userId))->delete();
       $this->userModel->where(array("user_id" => $userId))->delete();
       $this->success("删除成功！");
   }

    function self() {
        $users_obj= M("admin");
        $userId=$_SESSION['ADMIN_ID'];
        $user=$users_obj->where("user_id=$userId")->find();

//        $agentIdArr = D('Agent')
//            ->where(array('enterprise_code'=>$user['enterprise_code']))
//            ->select();
//        $userAgentIdArr = explode(",", $user["agent_id"]);
//
//        $list = array();
//        foreach ($agentIdArr as $agent){
//            if(in_array($agent["agent_id"], $userAgentIdArr)){
//                $list[] = array("agent_id" => $agent["agent_id"], "agent_name" => $agent["agent_name"], "has_agent" => 1);
//            }else{
//                $list[] = array("agent_id" => $agent["agent_id"], "agent_name" => $agent["agent_name"]);
//            }
//
//        }
//        $this->assign("list", $list);
        $this->assign('first', $_REQUEST["first"]);
        $this->assign('user', $user);
        $this->display();
    }
    function selfPost() {
        if (IS_POST) {
                $password = I('post.password');

                $users_obj= M("admin");
                $userId=$_SESSION['ADMIN_ID'];
                $user=$users_obj->where("user_id=$userId")->find();

                if(!isNullOrEmpty($password)){
                    $user['password'] = md5($password);
                }

//                $user['admin_name'] = I('post.adminName');
                $user['mobile'] = I('post.mobile');

                $user['update_time'] = getCurrentDate();

                $user['update_id'] = $user["employee_id"];

                $this->userModel->where(array('user_id'=>$userId))->save($user);

                $this->success("更新成功！", U("User/self"));
            }

    }
}